//
//  PhotoBrowserController.swift
//  SinaWeibo
//
//  Created by 林柱强 on 16/2/11.
//  Copyright © 2016年 林柱强. All rights reserved.
//

import UIKit
import SVProgressHUD

private let photoBrowserReuseIdentifier = "pictureCell"

class PhotoBrowserController: UIViewController {

    var currentIndex: Int?
    var pictureURL: [NSURL]?
    
    init(index: Int, url: [NSURL]) {
        //先初始化本类，在初始化父类
        currentIndex = index
        pictureURL = url
        super.init(nibName: nil, bundle: nil)

    }

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        
        //初始化UI
        setupUI()
    }
    
    private func setupUI() {
        //添加控件
        view.addSubview(collectionView)
        view.addSubview(closebtn)
        view.addSubview(savebtn)
        
        //设置布局
        closebtn.xmg_AlignInner(type: XMG_AlignType.BottomLeft, referView: view, size: CGSize(width: 100, height: 35), offset: CGPoint(x: 10, y: -10))
        
        savebtn.xmg_AlignInner(type: XMG_AlignType.BottomRight, referView: view, size: CGSize(width: 100, height: 35), offset: CGPoint(x: -10, y: -10))
        
        collectionView.frame = UIScreen.mainScreen().bounds
        
        //添加数据源
        collectionView.dataSource = self
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: photoBrowserReuseIdentifier)
    }
    
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func save() {
        //拿到当前正显示的cell
        let index = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(index) as! PhotoBrowserCell
        //保存图片
        let image = cell.iconView.image
        
        UIImageWriteToSavedPhotosAlbum(image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
        
        //- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    }
    
    func image(image: UIImage, didFinishSavingWithError error :NSError?, contextInfo: AnyObject) {
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存图片失败")
        }else {
            SVProgressHUD.showSuccessWithStatus("保存图片成功")
        }
    }
    
    
    //MARK: 懒加载控件
    private lazy var closebtn: UIButton = {
       let btn = UIButton()
        btn.setTitle("关闭", forState: .Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.backgroundColor = UIColor.darkGrayColor()
        
        btn.addTarget(self, action: "close", forControlEvents: .TouchUpInside)
        return btn
    }()
    
    private lazy var savebtn: UIButton = {
        let btn = UIButton()
        btn.setTitle("保存", forState: .Normal)
        btn.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        btn.backgroundColor = UIColor.darkGrayColor()
        
        btn.addTarget(self, action: "save", forControlEvents: .TouchUpInside)
        return btn
    }()
    
    private lazy var collectionView:UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: PhotoBrowserLayout())
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

extension PhotoBrowserController: UICollectionViewDataSource, PhotoBrowserCellDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureURL?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(photoBrowserReuseIdentifier, forIndexPath: indexPath) as! PhotoBrowserCell
        
        cell.backgroundColor = UIColor.randomColor()
        cell.imageUrl = pictureURL![indexPath.item]
        cell.photoBrowserCellDelegate = self
        
        return cell
    }
    
    func photoBrowserCellDidClose(cell: PhotoBrowserCell) {
        dismissViewControllerAnimated(true, completion: nil)
    }
}

class PhotoBrowserLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        itemSize = UIScreen.mainScreen().bounds.size
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        scrollDirection = .Horizontal
        
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.pagingEnabled = true
        collectionView?.bounces = false
    }
}
